import React, { Component } from 'react'
import { Row, Col, Icon, List, Divider, Badge, Input, message } from 'antd'
import moment from 'moment'
import { Link } from 'umi'
import Author from '@/components/Author'
import Advert from '@/components/Advert'
import { imageArr } from '@/assets/js/ConstVariable'
import { getArticleTypeAndAmount, getArticleByTag } from '@/services/list'
import './index.less'

import hljs from 'highlight.js'
import MarkdownIt from 'markdown-it'
import 'highlight.js/styles/atom-one-light.css'
import { serverBaseUrl } from '@/assets/js/ConstVariable'

const _ = require('lodash')
const mdParser = MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value
      } catch (__) {}
    }
    return '' // 使用额外的默认转义
  },
})
export default class Home extends Component {
  state = {
    articleList: [],
    articleType: '',
    articleTypeArr: [],
    tagId: 0,
  }
  componentDidMount() {
    this.handleTagsClick(this.state.tagId, '所有文章')
    this.getArticleTypeAndAmount()
  }

  // 获取文章类型和数量
  getArticleTypeAndAmount = async () => {
    const res = await getArticleTypeAndAmount()
    this.setState({ articleTypeArr: res.data })
  }

  // 文章类型图标点击
  handleTagsClick = async (id, articleType) => {
    const res = await getArticleByTag(id)
    this.setState({ articleList: res.data, articleType, tagId: id })
  }

  // 搜索
  handleSearchArticle = (value) => {
    if (value.length === 0) {
      return this.handleTagsClick(this.state.tagId, this.state.articleType)
    }
    let articleList = [...this.state.articleList]
    articleList = articleList.filter((item) => item.title.includes(value) || item.introduce.includes(value))
    this.setState({ articleList })
    if (articleList.length > 0) {
      message.success(`成功查询到${articleList.length}篇文章~`)
    } else {
      message.info('暂无相关文章~')
    }
  }
  render() {
    const { articleType, articleTypeArr, articleList } = this.state
    return (
      <div className="list">
        <Row className="comm-main" type="flex" justify="center">
          <Col className="comm-left" xs={24} sm={24} md={16} lg={18} xl={14}>
            <div className="classification">
              <header>
                <span className="sort-icon">
                  <Icon type="forward" />
                </span>
                <span>分类</span>
              </header>

              <main>
                <Row type="flex">
                  <Col span={5} key="0" onClick={() => this.handleTagsClick(0, '所有文章')}>
                    <Icon type="font-colors" />
                    &nbsp; 所有文章
                  </Col>
                  {articleTypeArr.map((item, index) => {
                    return (
                      <Col span={5} key={index + 1} onClick={() => this.handleTagsClick(item.tag_id, item.tag_name)}>
                        <Icon type={item.icon} /> &nbsp;
                        {item.tag_name}
                      </Col>
                    )
                  })}
                </Row>
              </main>
            </div>
            {/* 分割线 */}
            <Divider orientation="left" className="global-divider">
              {articleType}&nbsp;
              <Icon type="caret-down" />
            </Divider>
            {/* 搜索框 */}
            <Input.Search
              style={{ margin: '10px 0' }}
              placeholder="请输入文章关键字"
              onSearch={this.handleSearchArticle}
              enterButton
              allowClear
            />
            {/* 文章列表 */}
            <List
              itemLayout="vertical"
              dataSource={this.state.articleList}
              pagination={{
                pageSize: 5,
                hideOnSinglePage: true,
              }}
              renderItem={(item) => (
                <List.Item>
                  <Row type="flex" align="middle">
                    <Col span={6}>
                      <img
                        src={item?.url?.length ? serverBaseUrl + item.url : imageArr[~~(Math.random() * 5)]?.href}
                        alt="图片已失效"
                        className="cover"
                      />
                    </Col>
                    <Col span={18}>
                      <Link to={{ pathname: '/detail/' + item.id }}>
                        <div className="list-title">{item.title}</div>
                      </Link>
                      <div className="list-icon">
                        <span style={{ color: 'rgb(84,115,135)' }}>
                          <Icon type="calendar" /> {moment(Number(item.addTime * 1000)).format('YYYY-MM-DD HH:mm:ss')}
                        </span>
                        <span style={{ color: 'orange' }}>
                          <Icon type={item.tagIcon} /> {item.tagName}
                        </span>
                        <span style={{ color: 'tomato' }}>
                          <Icon type="fire" theme="filled" /> {item.viewCount}
                        </span>
                      </div>
                      <div
                        className="list-content"
                        dangerouslySetInnerHTML={{ __html: mdParser.render(item.introduce || '') }}
                      />
                    </Col>
                  </Row>
                </List.Item>
              )}
            />
          </Col>
          <Col xs={0} sm={0} md={7} lg={5} xl={4}>
            <Author />
            <Advert />
          </Col>
        </Row>
      </div>
    )
  }
}
